package org.gl.training.planner.service;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.gl.training.planner.dao.UserDao;
import org.gl.training.planner.model.Constants;
import org.gl.training.planner.model.User;

@ManagedBean(name = "loginBean")
@RequestScoped
public class LoginBean {

	private String userName;

	private String password;

	private String errorMessage;

	@ManagedProperty(value = "#{dataHolderBean}")
	private DataHolderBean dataHolderBean;

	@ManagedProperty(value = "#{userDao}")
	private UserDao userDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public String getUserName() {
		return userName;
	}

	public String getPassword() {
		return password;
	}

	public void setDataHolderBean(DataHolderBean dataHolderBean) {
		this.dataHolderBean = dataHolderBean;
	}

	public DataHolderBean getDataHolderBean() {
		return dataHolderBean;
	}

	public void setPassword(String password) {
		this.password = DigestUtils.md5Hex(password);
	}

	public String login() {
		if (StringUtils.isEmpty(userName)) {
			errorMessage = "Username is empty";
			return null;
		} else if (StringUtils.isEmpty(password)) {
			errorMessage = "Password is empty";
			return null;
		}

		User user = userDao.getUser(userName);

		if (user == null) {
			errorMessage = "User is not registered";
		} else if (!user.getPassword().equals(password)) {
			errorMessage = "User password is not correct";
		} else if (!user.getUserStatus().equals(Constants.USER_STATUS_APPROVED)) {
			errorMessage = "User is waiting for approve";
		} else {
			dataHolderBean.setUser(user);
			return "success";
		}

		return null;
	}
}
